package com.alibaba.dubbo.remoting.msgcodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.alibaba.dubbo.remoting.MessageDecode;
import com.alibaba.dubbo.remoting.MessageEncodeRegistry;

public class BridgeDecodeInputStream extends InputStream{
	
	private MessageDecode decoder;
	private InputStream in;
	private ByteArrayInputStream bais;
	//private MessageEncodeRegistry registry;
	public BridgeDecodeInputStream(MessageDecode decoder, InputStream in/*, MessageEncodeRegistry registry*/) throws IOException{
		this.decoder = decoder;
		this.in = in;
		//this.registry = registry;
		if(this.decoder != null){
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			decoder.decode(this.in, baos/*, this.registry*/);
			bais = new ByteArrayInputStream(baos.toByteArray());
		}
	}
	
	
	@Override
	public void close() throws IOException{
		super.close();
		if(bais != null){
			bais.close();
		}
	}


	@Override
	public int available() throws IOException {
		if(this.bais != null){
			return bais.available();
		}else{
			return in.available();
		}
	}


	@Override
	public synchronized void mark(int readAheadLimit) {
		if(this.bais != null){
			bais.mark(readAheadLimit);
		}else{
			in.mark(readAheadLimit);
		}
	}


	@Override
	public int read() throws IOException {
		if(this.bais != null){
			return bais.read();
		}else{
			return in.read();
		}
	}


	@Override
	public int read(byte[] b, int offset, int len) throws IOException {
		if(this.bais != null){
			return bais.read(b, offset, len);
		}else{
			return in.read(b, offset, len);
		}
	}


	@Override
	public int read(byte[] b) throws IOException {
		if(this.bais != null){
			return bais.read(b);
		}else{
			return in.read(b);
		}
	}


	@Override
	public long skip(long l) throws IOException {
		if(this.bais != null){
			return bais.skip(l);
		}else{
			return in.skip(l);
		}
	}
	
	  
}
